package com.unibeta.cloudtest.mesher.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.unibeta.cloudtest.mesher.auth.annotation.Authorization;
import com.unibeta.cloudtest.mesher.auth.bean.AuthUserDetails;
import com.unibeta.cloudtest.mesher.auth.service.AuthorizationService;
import com.unibeta.cloudtest.mesher.dto.PasswordChange;
import com.unibeta.cloudtest.mesher.dto.R;
import com.unibeta.cloudtest.mesher.modules.upm.entity.User;
import com.unibeta.cloudtest.mesher.util.IpUtil;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/upm")
@Slf4j
public class UpmController {

	@Autowired
	AuthorizationService authorizationService;

	@PostMapping("/register")
	public R<User> register(@RequestBody User user) {

		try {
			return R.ok(authorizationService.register(new AuthUserDetails(user)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return R.fail(e.getMessage());
		}
	}

	@PostMapping("/login")
	public R<String> login(@RequestBody User user, HttpServletRequest request) {
		String token = null;
		try {
			user.setLastLoginIp(IpUtil.getIpAddr(request));
			token = authorizationService.login(new AuthUserDetails(user));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return R.fail(e.getMessage());
		}

		return R.ok(token);
	}

	@PostMapping("/changePassword")
	@Authorization
	public R<Boolean> changePassword(@RequestBody PasswordChange passwordChange) {

		try {
			authorizationService.changePassword(passwordChange.getUsername(), passwordChange.getOldPassword(),
					passwordChange.getNewPassword(), passwordChange.getConfirmPassword());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return R.fail(e.getMessage());
		}

		return R.ok();
	}
}
